/**
 * 对本地化脚本错误做的临时hack
 * 在build后执行，指定要下载的文件和目录
 */

const path = require('path');
const chalk = require('chalk');
const download = require('download');
const fs = require('fs-extra');
const glob = require('glob');
const parseArgs = require('yargs-parser');

const gitGroup = process.env.BUILD_GIT_GROUP || '';
const gitProject = process.env.BUILD_GIT_PROJECT || '';
const gitBranch = process.env.BUILD_GIT_BRANCH || '';
const gitBranchParts = gitBranch.split('/');
const assetsVersion = gitBranchParts[gitBranchParts.length - 1];
const buildArgv = parseArgs(process.env.BUILD_ARGV_STR || '') || {};
const defOriginBranch = buildArgv.def_publish_devbranches;

// release/x.x.x 分支才做本地化
if (defOriginBranch && !defOriginBranch.startsWith('release/')) {
  return; // eslint-disable-line
}

const destDir = path.join(__dirname, '../build/downloads/');

const downloadFile = async (url, dir = '', filename) => {
  const rawUrl = /^http/.test(url) ? url : `https:${url}`;
  const destDownloadDir = `${destDir}${dir}`;
  try {
    await download(rawUrl, destDownloadDir, {
      filename,
    });
    console.log(chalk.green(`Download ${url} successfully`));
    return `${destDownloadDir}${filename}`;
  } catch (err) {
    console.error(err);
  }
};

downloadFile('//g.alicdn.com/code/lib/require.js/2.3.6/require.js', '/code_lib_require.js/2.3.6/', 'require.js');
